<script setup lang="ts">
import { computed, useSlots, reactive, ref } from "vue";
import { SearchOutlined, RollbackOutlined } from "@ant-design/icons-vue";

defineOptions({ name: "WebxSearch" });
const emits = defineEmits(["reset", "submit"]);
const props = defineProps({
  // 默认显示表单项的数量
  visibleCount: { type: Number, default: 3 }
});

const slots = useSlots();
const webxSearchRef = ref();
// 组件属性
const webxSearch = reactive({
  // true-收起，false-展开
  collapsed: true,
  // 重置查询
  async onReset() {
    // 表单重置
    await webxSearchRef.value.resetFields();
    // 执行重置
    emits("reset");
  },
  // 查询
  async onSubmit() {
    // 表单校验
    await webxSearchRef.value.validate();
    // 开始查询
    emits("submit");
  }
});

// 计算实际表单项数量
const itemCount = computed(() => {
  return slots.default?.().filter(node => (node.type?.name as string) === "AFormItem") || [];
});
// 判断是否需要折叠功能
const needCollapse = computed(() => itemCount.value.length > props.visibleCount);
</script>

<template>
  <AForm
    layout="inline"
    ref="webxSearchRef"
    v-bind="$attrs"
    class="webx-search bg-white rounded p-4"
  >
    <!-- 表单项容器 -->
    <template v-for="(formItem, index) in itemCount" :key="index">
      <component
        :is="formItem"
        v-if="!needCollapse || index < visibleCount || !webxSearch.collapsed"
      />
    </template>

    <!-- 操作按钮区域 -->
    <AFormItem class="ml-auto">
      <div class="flex gap-2 items-center">
        <template v-if="needCollapse">
          <AButton type="link" @click="webxSearch.collapsed = !webxSearch.collapsed">
            {{ webxSearch.collapsed ? "展开" : "收起" }}
          </AButton>
        </template>
        <!-- 插槽，扩展按钮 -->
        <div>
          <slot name="searchLeft" />
        </div>
        <AButton type="primary" htmlType="submit" @click="webxSearch.onSubmit">
          <SearchOutlined />
          查询
        </AButton>
        <AButton @click="webxSearch.onReset">
          <RollbackOutlined />
          重置
        </AButton>
      </div>
    </AFormItem>
  </AForm>
</template>

<style scoped lang="less">
.webx-search {
  .ml-auto {
    margin-left: auto;
  }
}
</style>
